<template>
  <div class="app-container">
    <el-button type="success" @click="handleAddRole">{{ $t('permission.addRole') }}</el-button>

    <div class="block block-custom">
      <el-table :data="rolesList" style="width: 100%;margin-top:30px;" height="calc(85vh - 140px)" border>
        <el-table-column label="序号" prop="id" sortable="custom" align="center" width="80">
          <template slot-scope="scope">
            <span>{{ scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="角色名称" width="220">
          <template slot-scope="scope">{{ scope.row.roleName }}</template>
        </el-table-column>
        <el-table-column align="center" label="角色描述">
          <template slot-scope="scope">{{ scope.row.introduction }}</template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <el-button type="primary" size="small" @click="handleEdit(scope)">编辑权限</el-button>
            <el-button :disabled="scope.row.roleId == 1 || scope.row.roleId == 2" type="danger" size="small" @click="handleDelete(scope)">删除角色</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <el-dialog :visible.sync="dialogVisible" :title="dialogType === 'edit' ? '修改角色' : '创建角色'" class="view-dialog" :modal="true" :show-close="false">
      <el-form ref="roleForm" :model="roleForm" label-position="left" label-width="40%" style="width:60%;" :rules="rules">
        <el-form-item label="角色名" prop="roleName">
          <el-input v-model="roleForm.roleName" placeholder="请输入角色名" />
        </el-form-item>
        <el-form-item label="角色介绍">
          <el-input v-model="roleForm.introduction" :autosize="{ minRows: 2, maxRows: 4 }" type="textarea" placeholder="请输入角色相关说明信息" />
        </el-form-item>
        <el-form-item label="权限管理" prop="menuCheck">
          <el-tabs v-model="activeName" type="border-card">
            <el-tab-pane label="终端菜单" name="menu">
              <el-tree ref="tree" :data="allPermission" :props="defaultProps" show-checkbox highlight-current node-key="name" class="permission-tree" />
            </el-tab-pane>
          </el-tabs>
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="dialogVisible = false">{{ $t('permission.cancel') }}</el-button>
        <el-button type="primary" @click="confirmRole">{{ $t('permission.confirm') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { deepClone } from '@/utils'
import { checkRegistered, getRoles, getOpPermissions, deleteRole, updateRole, addOrUpdateRole } from '@/api/role'

const defaultRole = {
  roleId: '',
  roleName: '',
  introduction: '',
  permission: [],
  op_perm: []
  // HT_menu_perm: []
}

export default {
  data() {
    var checkRoleName = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('角色名为必填项'))
      }
      setTimeout(() => {
        if (this.roleForm.roleName == this.roleFormBeforeChange.roleName) {
          callback()
        } else {
          checkRegistered(value).then(res => {
            if (res.code !== 0) {
              callback(new Error(res.msg))
            } else {
              callback()
            }
          })
        }
      }, 1000)
    }
    var checkMenuCheck = (rule, value, callback) => {
      // const checkedKeys = this.$refs.HTtree.getCheckedNodes()
      // const halfCheckedKeys = this.$refs.HTtree.getHalfCheckedNodes()
      // let HTcheckedList = [...checkedKeys, ...halfCheckedKeys]

      let resultPermission = this.dealPermission()
      // 盯控终端菜单
      this.roleForm.permission = resultPermission

      // 手持终端菜单
      // this.roleForm.HT_menu_perm = HTcheckedList
      if (resultPermission.length == 0) {
        var str = ''
        if (resultPermission.length == 0) str += '"盯控终端菜单"  '

        str += '至少勾选一项'
        return callback(new Error(str))
      } else {
        return callback()
      }
    }
    return {
      rules: {
        roleName: [{ required: true, validator: checkRoleName, trigger: 'blur' }],
        menuCheck: [{ required: true, validator: checkMenuCheck, trigger: 'blur' }]
      },

      activeName: 'menu',
      op_perms: [],
      roleForm: Object.assign({}, defaultRole),
      roleFormBeforeChange: {},
      routes: [],
      rolesList: [],
      dialogVisible: false,
      dialogType: 'new',
      checkStrictly: false,
      defaultProps: {
        children: 'children',
        label: 'value'
      },

      allPermission: [
        {
          name: 'trainInfo',
          value: '机车监控',
          level: 1,
          children: []
        },

        {
          name: 'personInfo',
          value: '人员设备监控',
          level: 1,
          children: []
        },
        {
          name: 'gis',
          value: '电子地图',
          level: 1,
          children: [],
          disabled: true
        },
        {
          name: 'stationMap',
          value: '站场图',
          level: 1,
          children: []
        },

        {
          name: 'dynamicPlayback',
          value: '动态回放',
          level: 1,
          children: [
            {
              name: 'playback',
              children: [],
              value: '电子地图回放',
              level: 2
            },
            {
              name: 'playbackTwo',
              children: [],
              value: '站场图回放',
              level: 2
            }
          ]
        },
        {
          name: 'staticAnalysis',
          value: '统计分析',
          level: 1,
          children: [
            {
              name: 'dcMonthlyReportAnalysis',
              children: [],
              value: '调车月报统计',
              level: 2
            },
            {
              name: 'capabilityUtilizationRate',
              children: [],
              value: '能力利用率',
              level: 2
            },
            {
              name: 'classOutput',
              children: [],
              value: '班产量统计',
              level: 2
            },
            {
              name: 'classPlanCash',
              children: [],
              value: '班计划兑现统计',
              level: 2
            },
            {
              name: 'dcTaskPlanCash',
              children: [],
              value: '调车作业计划统计',
              level: 2
            },
            // {
            //   name: 'effectivenessAnalysis',
            //   children: [],
            //   value: '效能统计',
            //   level: 2
            // },
            {
              name: 'midStopTimeIndicator',
              children: [],
              value: '中停时统计',
              level: 2
            },
            // {
            //   name: 'reportAnalysis',
            //   children: [],
            //   value: '6点/18点报告统计',
            //   level: 2
            // },
            {
              name: 'technologicalTask',
              children: [],
              value: '车辆信息统计',
              level: 2
            },
            // {
            //   name: 'trainDynamic',
            //   children: [],
            //   value: '机车动态统计',
            //   level: 2
            // },
            // {
            //   name: 'jobTicket',
            //   children: [],
            //   value: '作业单统计',
            //   level: 2
            // },
            {
              name: 'trainRunningTrajectory',
              children: [],
              value: '车辆运行轨迹',
              level: 2
            },
            // {
            //   name: 'workloadAnalysis',
            //   children: [],
            //   value: '作业量统计',
            //   level: 2
            // },
            {
              name: 'exHaust',
              children: [],
              value: '非正常排风统计',
              level: 2
            }
          ]
        },
        {
          name: 'historyAlarm',
          value: '历史报警',
          level: 1,
          children: []
        },
        {
          name: 'maintenance',
          value: '维护管理',
          level: 1,
          children: [
            // {
            //   name: 'organization',
            //   value: '组织架构图',
            //   level: 2,
            //   children: []
            // },
            {
              name: 'account',
              value: '账户管理',
              level: 2,
              children: [
                {
                  name: 'user',
                  value: '用户管理',
                  level: 3,
                  children: []
                },
                {
                  name: 'role',
                  value: '角色管理',
                  level: 3,
                  children: []
                }
              ]
            },
            {
              name: 'systemState',
              value: '系统运行状态',
              level: 2,
              children: [
                {
                  name: 'STPStation',
                  value: 'STP2.0中心',
                  level: 3,
                  children: []
                },
                {
                  name: 'serverLink',
                  value: '综合预警服务',
                  level: 3,
                  children: []
                }
              ]
            },
            {
              name: 'update',
              value: '版本更新',
              level: 2,
              children: [
                {
                  name: 'apk',
                  value: '软件上传',
                  level: 3,
                  children: []
                }
              ]
            }
          ]
        }
      ],
      resultPermission: [
        {
          name: 'trainInfo',
          children: [
            {
              name: 'index',
              children: []
            }
          ]
        },
        {
          name: 'personInfo',
          children: [
            {
              name: 'index',
              children: []
            }
          ]
        },
        {
          name: 'trainInfo',
          children: [
            {
              name: 'index',
              children: []
            }
          ]
        },
        {
          name: 'personInfo',
          children: [
            {
              name: 'index',
              children: []
            }
          ]
        },
        {
          name: 'gis',
          children: [
            {
              name: 'index',
              children: []
            }
          ]
        },
        {
          name: 'stationMap',
          children: [
            {
              name: 'index',
              children: []
            }
          ]
        },

        {
          name: 'task',
          children: [
            {
              name: 'index',
              children: []
            }
          ]
        },
        {
          name: 'dynamicPlayback',
          children: [
            {
              name: 'playback',
              children: []
            },
            {
              name: 'playbackTwo',
              children: []
            }
          ]
        },
        {
          name: 'staticAnalysis',
          children: [
            {
              name: 'dcMonthlyReportAnalysis',
              children: []
            },
            {
              name: 'capabilityUtilizationRate',
              children: []
            },
            {
              name: 'classOutput',
              children: []
            },
            {
              name: 'classPlanCash',
              children: []
            },
            {
              name: 'dcTaskPlanCash',
              children: []
            },
            {
              name: 'effectivenessAnalysis',
              children: []
            },
            {
              name: 'midStopTimeIndicator',
              children: []
            },
            {
              name: 'reportAnalysis',
              children: []
            },
            {
              name: 'technologicalTask',
              children: []
            },
            {
              name: 'trainDynamic',
              children: []
            },
            {
              name: 'jobTicket',
              children: []
            },
            {
              name: 'trainRunningTrajectory',
              children: []
            },
            {
              name: 'workloadAnalysis',
              children: []
            },
            {
              name: 'exHaust',
              children: []
            }
          ]
        },
        {
          name: 'historyAlarm',
          children: [
            {
              name: 'index',
              children: []
            }
          ]
        },
        {
          name: 'historyZuoYeDan',
          children: [
            {
              name: 'index',
              children: []
            }
          ]
        },
        {
          name: 'maintenance',
          children: [
            // {
            //   name: 'organization',
            //   children: []
            // },
            {
              name: 'account',
              children: [
                {
                  name: 'user',
                  children: []
                },
                {
                  name: 'role',
                  children: []
                }
              ]
            },
            {
              name: 'systemState',
              children: [
                {
                  name: 'STPStation',
                  children: []
                },
                {
                  name: 'serverLink',
                  children: []
                }
              ]
            },
            {
              name: 'update',
              children: [
                {
                  name: 'apk',
                  children: []
                }
              ]
            }
          ]
        },
        {
          name: '*',
          children: []
        }
      ]
    }
  },
  computed: {
    routesData() {
      return this.routes
    }
  },
  created() {
    this.getRoles()
  },
  methods: {
    async getRoles() {
      const res = await getRoles()
      this.rolesList = res.data
      const op_perms = await getOpPermissions()
      this.op_perms = op_perms.data
    },
    // Reshape the routes structure so that it looks the same as the sidebar
    generatePermissionKey(permission) {
      let res = []
      for (let index = 0; index < permission.length; index++) {
        const element = permission[index]
        if (element.children.length === 0) {
          res.push(element.name)
        } else if (element.children.length === 1) {
          if (element.children[0].name === 'index') {
            res.push(element.name)
          } else {
            res.push(element.children[0].name)
          }
        } else {
          let temp = this.generatePermissionKey(element.children)
          res = res.concat(temp)
        }
      }
      return res
    },
    handleAddRole() {
      this.activeName = 'menu'
      this.roleForm = Object.assign({}, defaultRole)
      // if (this.$refs.tree) {
      //   this.$refs.tree.setCheckedNodes([])
      // }
      this.$nextTick(() => {
        this.$refs.tree.setCheckedNodes([])
        // this.$refs.HTtree.setCheckedNodes([])
        this.$refs.tree.setCheckedKeys(['gis'])
      })
      this.dialogType = 'new'
      this.dialogVisible = true
    },
    handleEdit(scope) {
      if (this.$refs['roleForm'] != undefined) {
        this.$refs['roleForm'].clearValidate()
      }
      this.activeName = 'menu'
      this.dialogType = 'edit'
      this.dialogVisible = true
      this.roleForm = deepClone(scope.row)
      this.roleFormBeforeChange = deepClone(scope.row)
      // this.roleForm.permission = this.resultPermission
      this.$nextTick(() => {
        this.$refs.tree.setCheckedNodes([])
        // this.$refs.HTtree.setCheckedNodes([])
        // console.log(this.roleForm);
        let permissionKey = this.generatePermissionKey(this.roleForm.permission)
        // gis现在设为主页，必须添加 20230803
        permissionKey.push('gis')
        this.$refs.tree.setCheckedKeys(permissionKey)
        let op_perm = this.roleForm.op_perm
        // let HT_menu_perm = this.roleForm.HT_menu_perm
        // this.$refs.HTtree.setCheckedNodes(HT_menu_perm)
      })
    },
    handleDelete({ $index, row }) {
      this.$confirm('确认删除该角色吗？', '警告', {
        confirmButtonText: '确认删除',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          await deleteRole(row.roleId).then(res => {
            if (res.code === 0) {
              this.getRoles()
              this.$message.success('角色删除成功！')
            } else {
              this.$message.error(res.msg)
            }
          })
          // this.rolesList.splice($index, 1)
          // this.$message({
          //   type: 'success',
          //   message: 'Delete succed!'
          // })
        })
        .catch(err => {
          console.error(err)
        })
    },
    dealPermission() {
      const checkedKeys = this.$refs.tree.getCheckedKeys()
      const halfCheckedKeys = this.$refs.tree.getHalfCheckedKeys()
      let checkedList = [...checkedKeys, ...halfCheckedKeys]
      checkedList.push('*')
      checkedList.push('index')
      let resultPermission = deepClone(this.resultPermission)
      let permission = this.dealCheckedPermission(resultPermission, checkedList)
      return permission
    },
    confirmRole() {
      this.$refs['roleForm'].validate(valid => {
        if (valid) {
          // const checkedKeys = this.$refs.HTtree.getCheckedNodes()
          // const halfCheckedKeys = this.$refs.HTtree.getHalfCheckedNodes()
          // let HTcheckedList = [...checkedKeys, ...halfCheckedKeys]

          let resultPermission = this.dealPermission()
          // 盯控终端菜单
          this.roleForm.permission = resultPermission
          // 手持终端菜单
          // this.roleForm.HT_menu_perm = HTcheckedList
          if (resultPermission.length != 0) {
            addOrUpdateRole(this.roleForm).then(res => {
              if (res.code === 0) {
                this.dialogVisible = false
                this.getRoles()
                this.$message.success('角色更新成功！')
              } else {
                this.$message.error(res.msg)
              }
            })
          } else {
            callback()
          }
        } else {
          callback()
        }
      })
    },
    dealCheckedPermission(resultPermission, checkedList) {
      let bFlagFinish = false
      if (resultPermission.length === 0) {
        return resultPermission
      }
      while (!bFlagFinish) {
        for (let index = 0; index < resultPermission.length; index++) {
          let element = resultPermission[index]
          if (this.judgePermissionChecked(element.name, checkedList)) {
            element.children = this.dealCheckedPermission(element.children, checkedList)
          } else {
            resultPermission.splice(index, 1)
            break
          }
          if (index === resultPermission.length - 1) {
            bFlagFinish = true
          }
        }
      }
      return resultPermission
    },
    judgePermissionChecked(name, checkedList) {
      for (let index = 0; index < checkedList.length; index++) {
        const element = checkedList[index]
        if (name.includes(element)) {
          return true
        }
      }
      return false
    }
  }
}
</script>

<style scoped>
/deep/ .dialog-content .el-dialog__body {
  height: 40vh;
  overflow: auto;
}

/deep/ .view-dialog > .el-dialog {
  display: flex;
  flex-direction: column;
  margin: 0 !important;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 2px 2px 5px #d0d0d0;
  max-height: calc(100%);
  max-width: calc(100%);
}

/deep/ .el-dialog .el-dialog__body {
  flex: 1;
  overflow: hidden auto;
  /* 隐藏水平滚动条，显示垂直滚动条 */
  /* overflow-y: scroll; 显示垂直滚动条 */
}

/deep/ .view-dialog > .el-dialog > .el-dialog__header {
  width: 100%;
  height: 54px;
  line-height: 54px;
  text-align: center;
  background: #f4f5f7;
  border-radius: 12px 12px 0px 0px;
  font-size: 20px;
  font-family: Source Han Sans CN;
  font-weight: 400;
  color: #252b3a;
  padding: 0 0 0 40px;
  padding-left: 0;
}

/deep/ .view-dialog > .el-dialog > .el-dialog__footer {
  padding-left: 0;
  padding-right: 0;
  text-align: center;
}

/deep/ .dialog-form > .el-form-item {
  margin-bottom: 30px;
}

/deep/ .dialog-form > .el-form-item > .el-form-item__content > .el-input > .el-input__inner {
  width: 220px;
  height: 34px;
  background: #ffffff;
  border: 1px solid #dcdee2;
  border-radius: 3px;
}

/deep/ .dialog-form > .el-form-item > .el-form-item__content > .el-select > .el-input > .el-input__inner {
  width: 220px;
  height: 34px;
  background: #ffffff;
  border: 1px solid #dcdee2;
  border-radius: 3px;
}

/deep/ .view-dialog > .el-dialog > .el-dialog__header > .el-dialog__headerbtn {
  top: 0;
}

/deep/ .view-dialog .el-form-item__content {
  width: 100%;
}

.app-container {
  .roles-table {
    margin-top: 30px;
  }

  .permission-tree {
    margin-bottom: 30px;
  }
}
</style>
